// ---------------------------------------------------------------------------------
//  Copyright (C) 2009 Chillisoft Solutions
//  
//  This file is part of the Habanero framework.
//  
//      Habanero is a free framework: you can redistribute it and/or modify
//      it under the terms of the GNU Lesser General Public License as published by
//      the Free Software Foundation, either version 3 of the License, or
//      (at your option) any later version.
//  
//      The Habanero framework is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU Lesser General Public License for more details.
//  
//      You should have received a copy of the GNU Lesser General Public License
//      along with the Habanero framework.  If not, see <http://www.gnu.org/licenses/>.
// ---------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using FireStarterModeller.BO;
using FireStarterModeller.UI.LookupLists;
using Habanero.Base;
using Habanero.BO;
using Habanero.BO.ClassDefinition;
using Habanero.Faces.Base;
using Habanero.Faces.Win;
using DockStyle=System.Windows.Forms.DockStyle;

namespace FireStarterModeller.UI
{
    /// <summary>
    /// This control containst th BOPanel with controls for editing the fields for this property as
    ///  well as a Rule Editor Control where the rules for the particular property type can be edited.
    /// </summary>
    public class DMPropertyEditorControl : UserControlWin, IBOEditorControl
    {
        private readonly IControlFactory _controlFactory;
        private DMPropRuleControl _propRuleControl;
        private IDMClass _dmClass;
        private DMSolution _dmSolution;


        private LookupTypeSelectorControl _lookupTypeSelectorControl;

        //private ITextBox PropertyNameTextBox { get; set; }
//        private DMPropRuleParameterControl _dmPropRuleParameterControl;
        /// <summary>
        /// Constructor for a <see cref="DMPropertyEditorControl"/>
        /// </summary>
        /// <param name="controlFactory"></param>
        public DMPropertyEditorControl(IControlFactory controlFactory)
        {
            _controlFactory = controlFactory;
            InitialiseControl();

        }

        private void InitialiseControl()
        {
            IGroupBox detailPanelGroupBox = SetupDetailPanelGroupBox();
            IGroupBox propRuleGroupBox = SetupPropRuleGroupBox();
            BorderLayoutManager layoutManager = _controlFactory.CreateBorderLayoutManager(this);
            layoutManager.AddControl(detailPanelGroupBox, BorderLayoutManager.Position.North);
            layoutManager.AddControl(propRuleGroupBox, BorderLayoutManager.Position.Centre);
            this.Height = 200 + 130;
        }

        private IGroupBox SetupDetailPanelGroupBox()
        {
            PanelBuilder panelBuilder = new PanelBuilder(_controlFactory);
            DetailPanelInfo = panelBuilder.BuildPanelForForm(ClassDef.Get<DMProperty>().UIDefCol["default"].UIForm);
            PropertyTypeFieldInfo = DetailPanelInfo.FieldInfos["PropertyTypeID"];
            PropertyTypeCombo = ((IExtendedComboBox) PropertyTypeFieldInfo.InputControl).ComboBox;
            PropertyTypeCombo.Items.Clear();
            PropertyTypeCombo.SelectedValueChanged += PropertyTypeCombo_SelectedValueChanged;
            
            IGroupBox detailPanelGroupBox = _controlFactory.CreateGroupBox();
            IPanel panel = DetailPanelInfo.Panel;
            panel.Dock = Habanero.Faces.Base.DockStyle.Fill;
            detailPanelGroupBox.Controls.Add(panel);
            detailPanelGroupBox.Height = 185;
            detailPanelGroupBox.Width = 220;
            return detailPanelGroupBox;
        }

        private void PropertyTypeCombo_SelectedValueChanged(object sender, EventArgs e)
        {
            SetAutoIncrementingEnable(false);
            var selectedValue = PropertyTypeCombo.SelectedValue;
            if (selectedValue != null && PropertyTypeCombo.SelectedItem.ToString() == "Int32")
            {
                SetAutoIncrementingEnable(true);
            }
        }

        private void SetAutoIncrementingEnable(bool enabled)
        {
            var autoIncrementingFieldInfo = ExtendedPropsPanelInfo.FieldInfos["AutoIncrementing"];
            if (autoIncrementingFieldInfo == null) return;
            autoIncrementingFieldInfo.LabelControl.Enabled = enabled;
        }

        private IGroupBox SetupPropRuleGroupBox()
        {
            IGroupBox propRuleGroupBox = _controlFactory.CreateGroupBox("Property Rules");
            propRuleGroupBox.Height = 200;
            ITabControl rulesTabControl = _controlFactory.CreateTabControl();
            rulesTabControl.Dock = Habanero.Faces.Base.DockStyle.Fill;
            propRuleGroupBox.Controls.Add(rulesTabControl);

            SetupExtendedPropsTabPage(rulesTabControl);
            SetupPropRulesTabPage(rulesTabControl);
            SetupLookupListTabPage(rulesTabControl);
            return propRuleGroupBox;
        }

        private void SetupPropRulesTabPage(ITabControl rulesTabControl)
        {
            ITabPage tabPage = _controlFactory.CreateTabPage("Prop Rules");
            rulesTabControl.TabPages.Add(tabPage);

            _propRuleControl = new DMPropRuleControl(_controlFactory)
                       {
                           Width = 250,
                           Height = 160,
                           Top = 15,
                           Left = 5,
                           Dock = DockStyle.Fill
                       };

            tabPage.Controls.Add(_propRuleControl);
        }

        private void SetupLookupListTabPage(ITabControl rulesTabControl)
        {
            ITabPage lookupPage = _controlFactory.CreateTabPage("Lookup List");
            rulesTabControl.TabPages.Add(lookupPage);

            _lookupTypeSelectorControl = new LookupTypeSelectorControl(new FireStarterFormsController(_controlFactory))
                    {Dock = DockStyle.Fill};

            lookupPage.Controls.Add(_lookupTypeSelectorControl);
        }

        private void SetupExtendedPropsTabPage(ITabControl rulesTabControl)
        {
            ITabPage extendedPropsTabPage = _controlFactory.CreateTabPage("Extended Props");
            rulesTabControl.TabPages.Add(extendedPropsTabPage);

            PanelBuilder panelBuilder = new PanelBuilder(_controlFactory);
            ExtendedPropsPanelInfo = panelBuilder.BuildPanelForForm(ClassDef.Get<DMProperty>().UIDefCol["ExtendedProps"].UIForm);
            
            IPanel panel = ExtendedPropsPanelInfo.Panel;
            panel.Dock = Habanero.Faces.Base.DockStyle.Fill;
            extendedPropsTabPage.Controls.Add(panel);
         
        }

        public IPanelInfo ExtendedPropsPanelInfo { get; private set; }
        public IPanelInfo DetailPanelInfo { get; private set; }

        public PanelInfo.FieldInfo PropertyTypeFieldInfo { get; private set; }

        public IBusinessObject BusinessObject
        {
            get { return DetailPanelInfo.BusinessObject; }
            set
            {
                if (DetailPanelInfo.BusinessObject == value) return;

                DetailPanelInfo.BusinessObject = value;
                DMProperty property = (DMProperty) value;
                _propRuleControl.Property = property;
                _lookupTypeSelectorControl.DMProperty = property;
                this.ExtendedPropsPanelInfo.BusinessObject = property;
                if (value == null) return;
                IDMClass dmClass = property.Class;
                if (dmClass == null || dmClass == _dmClass) return;

                _dmClass = dmClass;
                if (_dmSolution == _dmClass.Solution) return;
                _dmSolution = (DMSolution) dmClass.Solution;
                if (_dmSolution == null)
                {
                    PropertyTypeCombo.Items.Clear();
                    return;
                }
                PropertyTypeMapper controlMapper = (PropertyTypeMapper)PropertyTypeFieldInfo.ControlMapper;
                controlMapper.DMSolution = dmClass.Solution;
                controlMapper.LoadPropertyTypeCombo();
            }
        }


        public IBusinessObjectControl PropRuleControl
        {
            get { return _propRuleControl; }
        }

        public void DisplayErrors()
        {
            try
            {
                DetailPanelInfo.ApplyChangesToBusinessObject();
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        public void ClearErrors()
        {
            try
            {
                DetailPanelInfo.ClearErrorProviders();
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        #region Implementation of IBOEditorControl

        /// <summary>
        ///             Applies any changes that have occured in any of the Controls on this control's to their related
        ///             Properties on the Business Object.
        /// </summary>
        public void ApplyChangesToBusinessObject()
        {
            this.DetailPanelInfo.ApplyChangesToBusinessObject();
        }

        /// <summary>
        ///             Does the business object controlled by this control or any of its Aggregate or Composite children have and Errors.
        /// </summary>
        public bool HasErrors
        {
            get { throw new System.NotImplementedException(); }
        }

        /// <summary>
        ///             Does the Business Object controlled by this control or any of its Aggregate or Composite children have and warnings.
        /// </summary>
        public bool HasWarning
        {
            get { throw new System.NotImplementedException(); }
        }

        /// <summary>
        ///              Returns a list of all warnings for the business object controlled by this control or any of its children.
        /// </summary>
        public ErrorList Errors
        {
            get { throw new System.NotImplementedException(); }
        }

        /// <summary>
        ///             Does the business object being managed by this control have any edits that have not been persisted.
        /// </summary>
        /// <returns>
        /// </returns>
        public bool IsDirty
        {
            get { throw new System.NotImplementedException(); }
        }

        /// <summary>
        ///             Returns a list of all warnings for the business object controlled by this control or any of its children.
        /// </summary>
        /// <returns>
        /// </returns>
        public ErrorList Warnings
        {
            get { throw new System.NotImplementedException(); }
        }

        public IComboBox PropertyTypeCombo { get; private set; }

        #endregion
    }
}